package com.netty.coder;

import com.alibaba.fastjson.JSONObject;
import com.netty.constant.Constants;
import com.netty.model.SentBody;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.util.List;
import java.util.Map;
import java.util.Objects;


public class WebMessageDecoder extends MessageToMessageDecoder<BinaryWebSocketFrame> {

    @Override
    protected void decode(ChannelHandlerContext context, BinaryWebSocketFrame frame, List<Object> list) throws Exception {
        context.channel().attr(Constants.SessionConfig.PING_COUNT).set(null);
        ByteBuf buffer = frame.content();
        byte[] byteArray = new byte[buffer.capacity()];
        buffer.readBytes(byteArray);
        String result = new String(byteArray);
        SentBody sentBody = JSONObject.parseObject(result, SentBody.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(Objects.nonNull(jsonObject.get("data"))){
            sentBody.putAll(JSONObject.parseObject(jsonObject.getString("data"), Map.class));
        }
        list.add(sentBody);
    }
}
